package com.example.user.service;

import com.example.common.Code;
import com.example.common.ResultMessage;
import com.example.common.Token;
import com.example.common.User;
import com.example.user.dao.token.TokenMapper;
import com.example.user.dao.user.UserMapper;
import com.example.user.feign.CodeFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author kangshuai
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Resource
    private CodeFeign codeFeign;

    @Resource
    private UserMapper userMapper;

    @Resource
    private TokenMapper tokenMapper;

    @Override
    public ResultMessage<Boolean> register(String email, String passwd, String verifyCode) throws Exception {
        //判断验证码是否正确
        if (email.isEmpty() || passwd.isEmpty() || verifyCode.isEmpty()) {
            return ResultMessage.error("输入非法参数！", false);
        }

        ResultMessage<Boolean> resultMessage = codeFeign.verify(new Code().setEmail(email).setCode(verifyCode));
        if (resultMessage.getStatus() == 1) {
            return resultMessage;
        }

        //判断是否已经注册
        if (isRegister(email)) {
            return ResultMessage.error("邮箱已注册!", false);
        }

        //进行注册
        User user = new User();
        user.setEmail(email);
        user.setPassword(passwd);
        boolean b = userMapper.insertUser(user);
        if (b == true) {
            return ResultMessage.success(true);
        } else {
            return ResultMessage.error("服务错误异常", false);
        }

    }

    @Override
    public Boolean isRegister(String email) throws Exception {
        User user = userMapper.selectByEmail(email);
        if (user != null && !user.getEmail().isEmpty()) {
            return true;
        }
        return false;
    }

    @Override
    public Token login(String email, String passwd) throws Exception {
        User user = userMapper.selectByEmail(email);
        if (user == null) {
            return null;
        }

        if (!passwd.equals(user.getPassword())) {
            return null;
        }

        String uuid = UUID.randomUUID().toString();
        Token token = new Token();
        token.setEmail(email);
        token.setToken(uuid);

        boolean b = tokenMapper.insertAndUpdateToken(token);
        if (b == false) {
            return null;
        }
        return token;
    }

    @Override
    public String getInfoByToken(String token) throws Exception {
        Token result = tokenMapper.selectByToken(token);
        if(result != null) {
            return result.getEmail();
        }
        return null;
    }
}
